package ldh.im.fxgui.service;

import ldh.im.ImConfig;
import ldh.im.dto.base.OkResp;
import ldh.im.dto.business.message.MessageReadReq;
import ldh.im.fxbase.dao.ImMessageDao;
import ldh.im.fxbase.dao.ImSessionDao;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.data.pojo.status.ImMessageActionStatus;
import ldh.im.fxbase.data.pojo.status.ImMessageFileStatus;
import ldh.im.fxbase.rpc.service.RpcMessageService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.util.UiUtil;
import ldh.rpc.util.JsonUtil;
import ldh.rpc.cache.CacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 消息已读事件发送至服务器端，支持同步发送和异步方式
 * 当前采用异步发送：模型：生产消费模式
 *
 */
public class MessageReadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageReadService.class);
    private static final Long CACHE_TIME = 5 * 60 * 1000L; // 缓存5分钟
    public static final int BATCH_SIZE = 200;             // 未读消息众多时，采取批量操作，批量操作数量

    private ImMessageDao imMessageDao = BeanFactory.getInstance().getBean(ImMessageDao.class);
    private ImSessionDao imSessionDao = BeanFactory.getInstance().getBean(ImSessionDao.class);
    private RpcMessageService rpcMessageService = RpcUtil.getRpcBootstrap().getRpcConfig().getClientBean(RpcMessageService.class);
    private Map<String, Long> readHandingMap = new ConcurrentHashMap<>();

    // 异步处理消息集合
    private LinkedBlockingDeque<ImMessage> messageDeque = new LinkedBlockingDeque<>();

    // 保证实例只有唯一一个
    private static volatile MessageReadService MESSAGE_READ_SERVICE = new MessageReadService();

    public static MessageReadService getInstance() {
        return MESSAGE_READ_SERVICE;
    }

    private MessageReadService() {
        LOGGER.info("start message read service");
        ThreadPoolUtil.scheduleAtFixedRate(()->{
            doReadBusiness();
        }, 100, 1000, TimeUnit.MILLISECONDS);
//        ThreadPoolUtil.submitSpecial(()->{
//            doReadBusiness();
//        });
    }

    /**
     * 异步处理消息
     * @param sessionId
     * @param userId
     * @param messages
     * @return
     */
    public List<ImMessage> asyHandleReadMessage(Long sessionId, String userId, List<ImMessage> messages) {
        LOGGER.info("read messages add sessionId {}", sessionId);
        List<ImMessage> needHandleMessages = filterNeedHandleMessages(userId, messages);
        if (needHandleMessages.size() > 0) {
            messageDeque.addAll(needHandleMessages);
        }
        return new ArrayList<>();
    }

    /**
     * 多线程处理消息，当已读事件众多时，会将线程池中的线程耗尽，会出现界面卡死
     * @param sessionId
     * @param userId
     * @param messages
     * @return
     */
    public List<ImMessage> handleReadMessage(Long sessionId, String userId, List<ImMessage> messages) {
        LOGGER.info("read messages add sessionId {}", sessionId);

        List<ImMessage> needHandleMessageList = filterNeedHandleMessages(userId, messages);    // 改变状态的为已读的消息

        if (needHandleMessageList.size() > 0) {
            ThreadPoolUtil.submit(()->{
                try {
                    doBusinessReadMessages(userId, needHandleMessageList);
                } catch (Exception e) {
                    LOGGER.error("read message batch do business error {}", e);
                }
            });
        }

        return new ArrayList<>();
    }

    /**
     * 异步处理已读消息
     */
    private void doReadBusiness() {
        ExceptionUtil.catchException(()->{
            CacheService cacheService = RpcUtil.getRpcBootstrap().getRpcConfig().getCacheService();
            String userId = (String) cacheService.getCache(ImConfig.LOGIN_USER_ID);
            if (userId == null) {
                LOGGER.warn("获取登录用户失败!");
                Thread.sleep(10000);
                return null;
            }
            List<ImMessage> messages = pollMessages(BATCH_SIZE);
            doBusinessReadMessages(userId, messages);
            return null;
        }, "批量处理消息");
    }

    /**
     * 业务处理主方法
     * @param userId
     * @param needHandleMessageList
     */
    private void doBusinessReadMessages(String userId, List<ImMessage> needHandleMessageList) {
        Set<String> messageServerIdSet = new HashSet<>();         // 发送已读消息的serverId集合
        Set<String> messageIdSet = new HashSet<>();               // 需发送已读消息serverId集合，并改变为已读

        for (ImMessage message : needHandleMessageList) {
            messageServerIdSet.add(message.getServerId());
            if (message.getActionStatus() != ImMessageActionStatus.read) {
                messageIdSet.add(message.getServerId());
            }
            readHandingMap.putIfAbsent(message.getServerId(), System.currentTimeMillis());
        }

        if (messageServerIdSet.size() > 0) {
            try {
                changeActionStatus(userId, messageIdSet, needHandleMessageList);

                sendReadActionToServer(userId, messageServerIdSet);

                needHandleMessageList.forEach(m->m.setActionStatus(ImMessageActionStatus.readed));

                Map<Long, List<ImMessage>> sessionMessageMap = needHandleMessageList.stream().collect(Collectors.groupingBy(ImMessage::getSessionId));
                for(Long key : sessionMessageMap.keySet()) {
                    int size = sessionMessageMap.get(key).size();
                    this.reduceHotMessageTotal(key, size);
                }

                FxThreadUtil.runLater(()->{
                    UiUtil.uiUpdateMessages(needHandleMessageList);
                });
            } catch (Exception e) {
                LOGGER.error("read message sending to server failure", e);
            } finally {
                messageServerIdSet.forEach(id->readHandingMap.remove(id));
            }
        }
    }

    /**
     * 从缓存队列中批量获取可以处理的消息
     * @param size 获取消息最大数
     * @return
     * @throws InterruptedException
     */
    private List<ImMessage> pollMessages(int size) {
        List<ImMessage> messages = new ArrayList<>();
        for (int i=0; i<size; i++) {
            ImMessage message = messageDeque.poll();
            if (message != null) {
                messages.add(message);
            } else {
                break;
            }
        }
        return messages;
    }

    /**
     * 过滤掉不是未读的消息
     * @param userId
     * @param messages
     * @return
     */
    private List<ImMessage> filterNeedHandleMessages(String userId, List<ImMessage> messages) {
        List<ImMessage> needHandleMessages = new ArrayList<>();    // 改变状态的为已读的消息
        for (ImMessage message : messages) {
            if (message.isSender(userId)) continue;
            if (message.getActionStatus() != null && message.getActionStatus() != ImMessageActionStatus.none
                    && message.getActionStatus() != ImMessageActionStatus.read) continue;
            if (message.isAttachFile() && message.getFileStatus() != ImMessageFileStatus.downloaded) continue;
            if (readHandingMap.containsKey(message.getServerId())) {
                long time = readHandingMap.get(message.getServerId());
                if (System.currentTimeMillis() - time < CACHE_TIME) {
                    continue;
                }
            }
            needHandleMessages.add(message);
        }
        return needHandleMessages;
    }

    /**
     * 将已读事件批量分组，并发送到服务器端
     * @param userId
     * @param messageServerIdSet
     * @throws SQLException
     */
    private void sendReadActionToServer(String userId, Set<String> messageServerIdSet) throws SQLException {
        Set<String> midSet = new HashSet<>();
        int i = 0;
        int total = 0;
        for (String id : messageServerIdSet) {
            i++;
            midSet.add(id);
            if (i == BATCH_SIZE) {
                total += i;
                sendReadToServer(userId, midSet);
                midSet = new HashSet<>();
                i = 0;
            }
        }

        if (i>0) {
            total += i;
            sendReadToServer(userId, midSet);
        }
        LOGGER.info("send message to server size {}, 应该总数： {}", total, messageServerIdSet.size());
    }

    /**
     * 已读事件发送到服务器端
     * @param userId
     * @param messageServerIdSet
     * @throws SQLException
     */
    private void sendReadToServer(String userId, Set<String> messageServerIdSet) throws SQLException {
        MessageReadReq messageReadReq = new MessageReadReq();
        messageReadReq.setMessageIds(messageServerIdSet);

        LOGGER.info("read messages sending to server {}", JsonUtil.toJson(messageReadReq));
        OkResp okResp = rpcMessageService.sendReadMessages(messageReadReq);
        if (!okResp.isSuccess()) {
            LOGGER.error("发送已读消息失败");
        } else {
            if (messageServerIdSet.size() > 0) {
                imMessageDao.changeMessageActionStatus(userId, messageServerIdSet, ImMessageActionStatus.readed);
            }
        }
    }

    /**
     * 已读事件更新本地状态
     * @param userId
     * @param changeActionStatusServerIdSet
     * @param changeMessageList
     * @throws SQLException
     */
    private void changeActionStatus(String userId, Set<String> changeActionStatusServerIdSet, List<ImMessage> changeMessageList) throws SQLException {
        changeMessageList.forEach(m->m.setActionStatus(ImMessageActionStatus.read));
        if (changeActionStatusServerIdSet.size() > 0) {
            int i = 0;
            int total = 0;
            Set<String> changeIdSet = new HashSet<>();
            for (String serverId : changeActionStatusServerIdSet) {
                i++;
                changeIdSet.add(serverId);
                if (i == BATCH_SIZE) {
                    total += i;
                    imMessageDao.changeMessageActionStatus(userId, changeIdSet, ImMessageActionStatus.read);
                    changeIdSet = new HashSet<>();
                    i = 0;
                }
            }
            if (i > 0) {
                total += i;
                imMessageDao.changeMessageActionStatus(userId, changeIdSet, ImMessageActionStatus.read);
            }
            LOGGER.info("send message to change status size {}, 应该总数： {}", total, changeActionStatusServerIdSet.size());
        }
    }

    private void reduceHotMessageTotal(Long sessionId, int size) throws SQLException {
        imSessionDao.incrHotMessageNum(sessionId, -size);

        ImHotMessageSingleton.getInstance().incHotMessage(sessionId, -size);
    }
}
